package com.admin.kotlintest.base

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.GridView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import com.admin.kotlintest.custome.CircleImageView

/**
 * Created by admin on 2017/11/28.
 */

class AdapterHolder (context: Context, group: ViewGroup, viewId: Int, position: Int) {

    private var adapterViews: SparseArray<View>? = null
    private var position:Int = 0
    private var layoutId:Int = 0

    init {
        this.adapterViews = SparseArray<View>()
        contentView = LayoutInflater.from(context).inflate(viewId, group, false)
        contentView?.tag = this
        this.position = position
    }

    fun <T : View> getView(viewId: Int): T? {
        var view: View ? = adapterViews!!.get(viewId)
        if (view == null) {
            view = contentView?.findViewById<T>(viewId)
//            view!!.tag = viewId
            adapterViews?.put(viewId, view)
        }
        return view as T
    }

    fun getContentView(): View ?{
        return contentView
    }

    fun upDataPosition(position: Int) {
        this.position = position
    }


    /**
     * 通用的控件设置方法 自此以下
     * @param viewId
     * @param msg
     */
    fun setTextViewText(viewId: Int, msg: String) {
        val view = getView<TextView>(viewId)
        view?.text = msg
    }

    fun getImageView(viewId: Int): ImageView? {
        return getView(viewId)
    }

    fun getCircleImageView(viewId: Int): CircleImageView ?{
        return getView(viewId)
    }

    fun getCheckBox(viewId: Int): CheckBox ?{
        val bar = getView<CheckBox>(viewId)
        return bar
    }

    fun getButton(viewId: Int): Button ?{
        val bar = getView<Button>(viewId)
        return bar
    }

    companion object {
        private var contentView: View ?=null

        fun getAdapterHolder(context: Context, contentView: View?, group: ViewGroup, viewId: Int, position: Int): AdapterHolder {
            return if (contentView == null) {
                val holder = AdapterHolder(context, group, viewId, position)
                holder.layoutId = viewId
                holder
            } else {
                val holder = contentView.tag as AdapterHolder
                holder.position = position
                holder
            }
        }
    }

}
